package com.wiz.common.util;

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;

import org.apache.commons.codec.binary.Base64;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;


public final class ThreeDESUtil {
	public static void main(String[] args) throws Exception {
		
		String ork = "d15Q5Ia4";
		String okey = buildKey(ork.getBytes());
        byte[] key=new BASE64Decoder().decodeBuffer(okey);  
        System.out.println("==="+okey);
        byte[] keyiv = { 1, 2, 3, 4, 5, 6, 7, 8 };  
        byte[] data="{\"hqId\":\"16544\",\"memberName\":\"1\",\"cardNo\":\"1\",\"phoneNum\":\"1\",\"pageNo\":1,\"pageSize\":10}".getBytes("UTF-8");  
          
//        System.out.println("ECB加密解密");  
//        byte[] str3 = des3EncodeECB(key,data );  
//        byte[] str4 = ees3DecodeECB(key, str3);  
//        System.out.println(new BASE64Encoder().encode(str3));  
//        System.out.println(new String(str4, "UTF-8"));  
//        System.out.println();  
        System.out.println("CBC加密解密");  
        byte[] str5 = des3EncodeCBC(key, keyiv, data);  
        String s = "pBJSEKJ3R206gIirpizqy9OWNF08+TyrF/20pBiIO3vGohZQMyuhTLf2U5TKbm5xFzimIDtxM/Uti++YyB7a7R6QjfV0Td/YuUI8v+sDeUgvf6o/1ggp9Q==";
        byte[] str6 = des3DecodeCBC(key, keyiv,new BASE64Decoder().decodeBuffer(s));  
        System.out.println(new BASE64Encoder().encode(str5));  
        System.out.println(new String(str6, "UTF-8"));  
    }  
	
	public static String buildKey(byte[] src) throws UnsupportedEncodingException{
		byte[] bs = {48,48,48,48,48,48,48,48,48,48,48,48,48,48,48,
				48,48,48,48,48,48,48,48,48,48,48,48,48,48,48,48,48};
		for(int i=0;i<src.length;i++){
			bs[i*4]=src[i];
		}
		return new String(bs,"UTF-8");
	}
	
    /** 
     * ECB加密,不要IV 
     * @param key 密钥 
     * @param data 明文 
     * @return Base64编码的密文 
     * @throws InvalidKeyException 
     * @throws NoSuchAlgorithmException 
     * @throws InvalidKeySpecException 
     * @throws NoSuchPaddingException 
     * @throws BadPaddingException 
     * @throws IllegalBlockSizeException 
     * @throws Exception 
     */  
    public static byte[] des3EncodeECB(byte[] key, byte[] data) throws Exception{  
        Key deskey = null;  
        DESedeKeySpec spec = new DESedeKeySpec(key);  
        SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");  
        deskey = keyfactory.generateSecret(spec);  
        Cipher cipher = Cipher.getInstance("desede" + "/ECB/PKCS5Padding");  
        cipher.init(Cipher.ENCRYPT_MODE, deskey);  
        byte[] bOut = cipher.doFinal(data);  
        return bOut;  
    }  
    /** 
     * ECB解密,不要IV 
     * @param key 密钥 
     * @param data Base64编码的密文 
     * @return 明文 
     * @throws Exception 
     */  
    public static byte[] ees3DecodeECB(byte[] key, byte[] data)  
            throws Exception {  
        Key deskey = null;  
        DESedeKeySpec spec = new DESedeKeySpec(key);  
        SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");  
        deskey = keyfactory.generateSecret(spec);  
        Cipher cipher = Cipher.getInstance("desede" + "/ECB/PKCS5Padding");  
        cipher.init(Cipher.DECRYPT_MODE, deskey);  
        byte[] bOut = cipher.doFinal(data);  
        return bOut;  
    }  
    /** 
     * CBC加密 
     * @param key 密钥 
     * @param keyiv IV 
     * @param data 明文 
     * @return Base64编码的密文 
     * @throws Exception 
     */  
    public static byte[] des3EncodeCBC(byte[] key, byte[] keyiv, byte[] data)  
            throws Exception {  
        Key deskey = null;  
        DESedeKeySpec spec = new DESedeKeySpec(key);  
        SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");  
        deskey = keyfactory.generateSecret(spec);  
        Cipher cipher = Cipher.getInstance("desede" + "/CBC/PKCS5Padding");  
        IvParameterSpec ips = new IvParameterSpec(keyiv);  
        cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);  
        byte[] bOut = cipher.doFinal(data);  
        return bOut;  
    }  
    /** 
     * CBC解密 
     * @param key 密钥 
     * @param keyiv IV 
     * @param data Base64编码的密文 
     * @return 明文 
     * @throws InvalidKeyException 
     * @throws NoSuchAlgorithmException 
     * @throws NoSuchPaddingException 
     * @throws InvalidKeySpecException 
     * @throws InvalidAlgorithmParameterException 
     * @throws BadPaddingException 
     * @throws IllegalBlockSizeException 
     * @throws Exception 
     */  
    public static byte[] des3DecodeCBC(byte[] key, byte[] keyiv, byte[] data) throws InvalidKeyException, 
    NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, 
    InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException  
            {  
        Key deskey = null;  
        DESedeKeySpec spec = new DESedeKeySpec(key);  
        SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");  
        deskey = keyfactory.generateSecret(spec);  
        Cipher cipher = Cipher.getInstance("desede" + "/CBC/PKCS5Padding");  
        IvParameterSpec ips = new IvParameterSpec(keyiv);  
        cipher.init(Cipher.DECRYPT_MODE, deskey, ips);  
        byte[] bOut = cipher.doFinal(data);  
        return bOut;  
    }  

    /**
     * 二行制转字符串
     * @param b
     * @return
     */
    public static String byte2hex(byte[] b) { // 一个字节的数，
        // 转成16进制字符串
        String hs="";
        String stmp="";
        for(int n=0; n < b.length; n++) {
            // 整数转成十六进制表示
            stmp=(java.lang.Integer.toHexString(b[n] & 0XFF));
            if(stmp.length() == 1)
                hs=hs + "0" + stmp;
            else
                hs=hs + stmp;
        }
        return hs.toUpperCase(); // 转成大写
    }

    private static byte[] hex2byte(byte[] b) {
        if((b.length % 2) != 0)
            throw new IllegalArgumentException("长度不是偶数");
        byte[] b2=new byte[b.length / 2];
        for(int n=0; n < b.length; n+=2) {
            String item=new String(b, n, 2);
            // 两位一组，表示一个字节,把这样表示的16进制字符串，还原成一个进制字节
            b2[n / 2]=(byte)Integer.parseInt(item, 16);
        }

        return b2;
    }
}
